<?php

namespace Mouta\AmistateBundle\Controller;

use Sonata\AdminBundle\Controller\CRUDController as Controller;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Sonata\AdminBundle\Datagrid\ProxyQueryInterface;

class SonataAdminUsuariosController extends Controller
{
    public function editAction($id = null)
    {
        $id = $this->get('request')->get($this->admin->getIdParameter());

        $object = $this->admin->getObject($id);

        if (!$object) {
            throw new NotFoundHttpException(sprintf('unable to find the object with id : %s', $id));
        }

        if (false === $this->admin->isGranted('EDIT', $object)) {
            throw new AccessDeniedException();
        }

        $this->admin->setSubject($object);

        $form = $this->admin->getForm();
        $form->setData($object);
        $txtFalsh = 'flash_edit_success';
        $txtFalshType = 'sonata_flash_success';

        if ($this->get('request')->getMethod() == 'POST') {
            if($this->get('request')->get('full-delete') ){
                if(ADMIN_USERNAME=="carlos"){
                    //TODO Borrar el usuario y todos los datos relacionados
                    $imgs = $object->getImagenes();
                    foreach($imgs as $img){
                        unlink($img->getPathImage().$img->getImagen());
                        unlink($img->getPathImage().$img->getImagenBig());
                    }
                    $em = $this->get('doctrine')->getEntityManager();
                    $em->remove($object);
                    $em->flush();
                    return new RedirectResponse($this->admin->generateUrl('list'));
                }else {
                    $txtFalsh = 'Datos Guardados pero solo Carlos puede borrar fisicamente un usuario';
                    $txtFalshType ='sonata_flash_error';
                }
            } 
            $form->bindRequest($this->get('request'));

            if ($form->isValid()) {
                $this->procesarFotos($object);
                $this->admin->update($object);
                $this->get('session')->setFlash($txtFalshType, $txtFalsh);

                if ($this->isXmlHttpRequest()) {
                    return $this->renderJson(array(
                        'result'    => 'ok',
                        'objectId'  => $this->admin->getNormalizedIdentifier($object)
                    ));
                }

                // redirect to edit mode
                return $this->redirectTo($object);
            }

            $this->get('session')->setFlash($txtFalshType, 'flash_edit_error');
        }

        $view = $form->createView();

        // set the theme for the current Admin Form
        $this->get('twig')->getExtension('form')->setTheme($view, $this->admin->getFormTheme());

        return $this->render('AmistateBundle:adminGlobal:edit_usuario.html.twig', array(
            'action' => 'edit',
            'form'   => $view,
            'object' => $object,
        ));
    }
    
    /**
     * @throws \Symfony\Component\HttpKernel\Exception\NotFoundHttpException|\Symfony\Component\Security\Core\Exception\AccessDeniedException
     * @param $id
     * @return \Symfony\Bundle\FrameworkBundle\Controller\Response|\Symfony\Component\HttpFoundation\RedirectResponse
     */
    public function deleteAction($id)
    {
        $id = $this->get('request')->get($this->admin->getIdParameter());
        $object = $this->admin->getObject($id);

        if (!$object) {
            throw new NotFoundHttpException(sprintf('unable to find the object with id : %s', $id));
        }

        if (false === $this->admin->isGranted('DELETE', $object)) {
            throw new AccessDeniedException();
        }

        if ($this->getRequest()->getMethod() == 'DELETE') {
            try {
                $object->setBorrado(true);
                $this->admin->update($object);
                $this->get('session')->setFlash('sonata_flash_success', 'flash_delete_success');
            } catch ( ModelManagerException $e ) {
                $this->get('session')->setFlash('sonata_flash_error', 'flash_delete_error');
            }

            return $this->redirectTo($object);
        }

        return $this->render('SonataAdminBundle:CRUD:delete.html.twig', array(
            'object' => $object,
            'action' => 'delete'
        ));
    }
    
    /**
     * execute a batch delete
     *
     * @throws \Symfony\Component\Security\Core\Exception\AccessDeniedException
     *
     * @param \Sonata\AdminBundle\Datagrid\ProxyQueryInterface $query
     *
     * @return \Symfony\Component\HttpFoundation\RedirectResponse
     */
    public function batchActionDelete(ProxyQueryInterface $query)
    {
        $um = $this->get('amistate.user_manager');
        $posts = $this->get('request')->request->get('idx');
        foreach($posts as $post){
            $usuario = $um->getUserById($post);
            $usuario->setBorrado(true);
            $um->actualizarUser($usuario);
        }
        return new RedirectResponse($this->admin->generateUrl('list', $this->admin->getFilterParameters()));
    }
    
    public function procesarFotos(&$user){
        $posts = $this->get('request')->request->all();
        $arrayDatos = array();
        foreach($posts as $key => $value){
            if(strpos($key, 'image_') === 0 )
            {
                $datos = explode('_', $key);
                $arrayDatos[$datos[2]][$datos[1]] = $value;
            }
        }
        $imagenDefault = null;
        if(isset($posts['imgdefa']))
            $imagenDefault = $posts['imgdefa'];
        /* @var $em \Doctrine\ORM\EntityManager */
        $em = $this->get('doctrine')->getEntityManager();
        foreach($arrayDatos as $id => $img){
            $image = $em->getRepository('AmistateBundle:ImagenUsuario')->findOneBy(array('id'=>$id));
            if(isset($img['borrar']))
            {//borro la imagen
                /* @var $user \Mouta\AmistateBundle\Entity\Usuario */
                $user->getImagenes()->removeElement($image);
                $em->remove($image);
                if(is_file($image->getPathImage().$image->getImagen()))
                    unlink ($image->getPathImage().$image->getImagen());
                if(is_file($image->getPathImage().$image->getImagenBig()))
                    unlink ($image->getPathImage().$image->getImagenBig());
            }else{//Actualizo la imagen
                $user->getImagenes()->get( $user->getImagenes()->indexOf($image) )->setLabel($img['label']);
                if($image->getId() == $imagenDefault)
                    $user->getImagenes()->get( $user->getImagenes()->indexOf($image) )->setDefa(1);
                else
                    $user->getImagenes()->get( $user->getImagenes()->indexOf($image) )->setDefa(0);
            }
        }
        $em->flush();
        $em->getRepository('AmistateBundle:ImagenUsuario')->actualizarDefault($user->getId());
    }
    
}